﻿using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using SyCODE.Component;

namespace SyCODE.Blog.Task
{
    /// <summary>
    /// 任务队列序列化功能的实现
    /// </summary>
    public static class Serialization
    {
        /// <summary>
        /// 序列化任务队列
        /// </summary>
        /// <param name="queue">任务队列</param>
        public static void Serialize(Queue<TaskBase> queue)
        {

            FileStream fs = File.Create(Path.Combine(AppPath.GetAppRootPath(), "task.bin"), 1024, FileOptions.WriteThrough);
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, queue);
        }

        /// <summary>
        /// 反序列化队列
        /// </summary>
        /// <returns></returns>
        public static Queue<TaskBase> Deserialize()
        {
            string taskStore = Path.Combine(AppPath.GetAppRootPath(), "task.bin");
            if (File.Exists(taskStore))
            {
                Queue<TaskBase> queue;
                FileStream fs = File.Open(taskStore, FileMode.Open, FileAccess.Read, FileShare.Delete);
                try
                {
                    IFormatter formatter = new BinaryFormatter();
                    queue = (Queue<TaskBase>)formatter.Deserialize(fs);
                }
                catch
                {
                    queue = new Queue<TaskBase>();
                }
                finally
                {
                    fs.Close();
                    File.Delete(taskStore);
                }
                return queue;
            }
            else
            {
                return new Queue<TaskBase>();
            }
        }
    }
}
